import { Injectable, Injector } from '@angular/core';
import { Constant, ServiceResult } from '@core/constant';
import { _HttpClient } from '@delon/theme';
import { MyHttpClient } from '../MyHttpClient';
import { HttpResponse } from '@angular/common/http';
import { saveAs } from 'file-saver';


@Injectable()
export class SmsService {

  get cnt(): Constant {
    return this.injector.get(Constant);
  }

  constructor(
    private injector: Injector,
    private http: _HttpClient,
    private myHttp: MyHttpClient
  ) { }

  /**
   * 查询物流记录
   * @param acode 
   * @param barcode 
   */
  queryLogistic(acode = '', barcode = '') {
    return this.http.get(`${this.cnt.baseUrl}/api/sms/log/code/getlogistice?acode=${acode}&barcode=${barcode}`);
  }

  /**
   * 分页查询交货单
   */
  queryDeliverys() {
    return `${this.cnt.baseUrl}/api/sms/log/delivery/list`;
  }

  /**
   * 获取blDelivery
   * @param deliveryId 
   */
  getDelivery(deliveryId) {
    return this.http.get(`${this.cnt.baseUrl}/api/sms/log/delivery/${deliveryId}`);
  }

  /**
   * 返回交货单明细
   * @param deliveryId 
   */
  getDeliveryDetail(deliveryId) {
    return this.http.get(`${this.cnt.baseUrl}/api/sms/log/delivery/detail/${deliveryId}`);
  }

  /** 
   * 导出发货明细
   */
  exportDeliveryDetail(deliveryId) {
    return `${this.cnt.baseUrl}/api/sms/log/delivery/export/detail/${deliveryId}`;
  }

  /**
   * 导出条码明细
   */
  exportDeliveryBarcode(deliveryId) {
    this.http.request('get', `${this.cnt.baseUrl}/api/sms/log/delivery/export/barcode/${deliveryId}`, {
      responseType: 'blob',
      observe: 'response'
    }).subscribe(
      (res: HttpResponse<Blob>) => {
        if (res.status !== 200 || res.body.size <= 0) {
          return;
        }
        // const disposition: any = this.getDisposition(res.headers.get('content-disposition'));
        const filename = `${deliveryId}条码明细`
        saveAs(res.body, decodeURI(filename));                                
      }
    )
  }
  
  private getDisposition(data: string) {
    const arr: any = (data || '')
      .split(';')
      .filter(i => i.includes('='))
      .map(v => {
        const strArr = v.split('=');
        const utfId = `UTF-8''`;
        let value = strArr[1];
        if (value.startsWith(utfId)) {
          value = value.substr(utfId.length);          
        }
        return { [strArr[0].trim()]: value}
      })
      return arr.reduce((o, item: any) => item, {});
  }

  /**
   * 1级客户发货撤销
   * @param barcode 
   */
  cancelAgent2Client(barcode) {
    return this.http.post(`${this.cnt.baseUrl}/api/sms/log/code/cancelagent2client?barcode=${barcode}`);
  }
}